package com.central.scheduler.master.registry;

import com.central.scheduler.common.Constants;
import com.central.scheduler.common.enums.NodeType;
import com.central.scheduler.service.bean.SpringApplicationContext;
import com.central.scheduler.spi.register.DataChangeEvent;
import com.central.scheduler.spi.register.SubscribeListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.central.scheduler.common.Constants.REGISTRY_SCHEDULER_MASTERS;
import static com.central.scheduler.common.Constants.REGISTRY_SCHEDULER_WORKERS;

/**
 * @author Tindy
 * @date 2021/11/3
 * @describe
 */
public class MasterRegistryDataListener implements SubscribeListener {

    private static final Logger logger = LoggerFactory.getLogger(MasterRegistryDataListener.class);

    private MasterRegistryClient masterRegistryClient;

    public MasterRegistryDataListener() {
        masterRegistryClient = SpringApplicationContext.getBean(MasterRegistryClient.class);
    }
    @Override
    public void notify(String path, DataChangeEvent event) {
        //monitor master
        if (path.startsWith(REGISTRY_SCHEDULER_MASTERS + Constants.SINGLE_SLASH)) {
            handleMasterEvent(event, path);
        } else if (path.startsWith(REGISTRY_SCHEDULER_WORKERS + Constants.SINGLE_SLASH)) {
            //monitor worker
            handleWorkerEvent(event, path);
        }
    }
    /**
     * monitor master
     *
     * @param event event
     * @param path path
     */
    public void handleMasterEvent(DataChangeEvent event, String path) {
        switch (event) {
            case ADD:
                logger.info("master node added : {}", path);
                masterRegistryClient.updateNodeInfoOnDB(path, NodeType.MASTER);
                break;
            case REMOVE:
                masterRegistryClient.removeNodePath(path, NodeType.MASTER, true);
                break;
            default:
                break;
        }
    }
    /**
     * monitor worker
     *
     * @param event event
     * @param path path
     */
    public void handleWorkerEvent(DataChangeEvent event, String path) {
        switch (event) {
            case ADD:
                logger.info("worker node added : {}", path);
                masterRegistryClient.updateNodeInfoOnDB(path, NodeType.WORKER);
                break;
            case REMOVE:
                logger.info("worker node deleted : {}", path);
                masterRegistryClient.removeNodePath(path, NodeType.WORKER, true);
                break;
            default:
                break;
        }
    }
}
